package com.simplecontact.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

import com.simplecontact.R;
import com.simplecontact.adapters.adIconText;
import com.simplecontact.classes.Contact;
import com.simplecontact.classes.ContactBundle;
import com.simplecontact.classes.GroupContact;
import com.simplecontact.classes.Groups;
import com.simplecontact.utils.Utils;

public class ActContact extends Activity {
	public static ListView lsv1;
	public static Integer idgroup;
	
	public int deleteGroupContact(int id, String idname){
		int row = getContentResolver().delete(GroupContact.GroupContactColumns.CONTENT_URI, idname + "=" + id, null);
		return row;
	}	
	public int deleteContact(int id){
		int row = getContentResolver().delete(Contact.ContactColumns.CONTENT_URI, "_id = " + id, null);
		lsv1 = (ListView)findViewById(R.id.listview1);				
		String[] arrImage = getContactImage();
		String[] arrName = getContactName();
		int[] arrId = getContactId();
		if(arrId!=null)
			lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
		else
			lsv1.setAdapter(null);
		return row;
	}
	public ContactBundle prepareToEditContact(int id){
		ContactBundle cb = null;
		Cursor c = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, null, null, null, null);				
        if (c.moveToFirst()) {        	
			int ColumnId = c.getColumnIndex(Contact.ContactColumns._ID);						
			int columnNickName = c.getColumnIndex(Contact.ContactColumns.NICKNAME);
			int columnFirstName = c.getColumnIndex(Contact.ContactColumns.FIRSTNAME);
			int columnLastName = c.getColumnIndex(Contact.ContactColumns.LASTNAME);
			int columnEmail = c.getColumnIndex(Contact.ContactColumns.EMAIL);
			int columnPhoneNumber = c.getColumnIndex(Contact.ContactColumns.PHONENUMBER);
			int columnImage = c.getColumnIndex(Contact.ContactColumns.IMAGE);
			int columnAddress = c.getColumnIndex(Contact.ContactColumns.ADDRESS);
			do {
				// Get the field values								
				if(c.getInt(ColumnId)==id){
					cb = new ContactBundle(id, c.getString(columnNickName),c.getString(columnFirstName),c.getString(columnLastName),c.getString(columnEmail),c.getString(columnAddress),c.getString(columnPhoneNumber),c.getString(columnImage));
					break;
				}
			} while (c.moveToNext());
		}
        return cb;
	}
	public String[] getContactName(){		
		Cursor c = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnFisrt = c.getColumnIndex(Contact.ContactColumns.FIRSTNAME);
			int ColumnLast = c.getColumnIndex(Contact.ContactColumns.LASTNAME);
			do {
				// Get the field values								
				str += (c.getString(ColumnFisrt) + " " + c.getString(ColumnLast));
				str +="\n";							
			} while (c.moveToNext());
		}
        String[] res = str.split("\n");
        if(res.length!=0)
        	return res;
        return null;
	}
	public String[] getContactImage(){
		Cursor c = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnImage = c.getColumnIndex(Contact.ContactColumns.IMAGE);			
			do {
				// Get the field values								
				str += (c.getString(ColumnImage));
				str +="\n";							
			} while (c.moveToNext());
		}
        String[] res = str.split("\n");
        if(res.length!=0)
        	return res;
        return null;
	}
	public int[] getContactId(){
		Cursor c = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnId = c.getColumnIndex(Contact.ContactColumns._ID);			
			do {
				// Get the field values								
				str += (c.getString(ColumnId));
				str +="\n";							
			} while (c.moveToNext());
		}
        int[] res = null;
        if(str.length()>0)str = str.substring(0, str.length()-1);
        if(str.length()!=0){
        	String[] temp = str.split("\n");
        	res = new int[temp.length];		                    
        	for(int i = 0 ; i < res.length ; i++){
        		res[i] = Integer.parseInt(temp[i]);
        	}
        }
		return res;
	}
	
	public ArrayList<Object> getContactNameBelongGroup(final int idg){
		final ArrayList<String> aitems = new ArrayList<String>();
		final ArrayList<String> aimages = new ArrayList<String>();
		final ArrayList<Integer> ids = new ArrayList<Integer>();		
		Cursor c = getContentResolver().query(GroupContact.GroupContactColumns.CONTENT_URI, new String[]{GroupContact.GroupContactColumns.CONTACTID}, GroupContact.GroupContactColumns.GROUPID + "=" + idg, null, null);
		if (c.moveToFirst()) {        	
			int ColumnFisrt = c.getColumnIndex(GroupContact.GroupContactColumns.CONTACTID);
			do {
				// Get the field values								
				int i = c.getInt(ColumnFisrt);
				Cursor c1 = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, null, Contact.ContactColumns._ID + "=" + i, null, null);
				if (c1.moveToFirst()) {
					int ColumnImage = c1.getColumnIndex(Contact.ContactColumns.IMAGE);
					int ColumnIndex = c1.getColumnIndex(Contact.ContactColumns._ID);					
					int ColumnFirst = c1.getColumnIndex(Contact.ContactColumns.FIRSTNAME);
					int ColumnLast = c1.getColumnIndex(Contact.ContactColumns.LASTNAME);
					do {
						aitems.add(c1.getString(ColumnFirst) + " " + c1.getString(ColumnLast));
						aimages.add(c1.getString(ColumnImage));
						ids.add(c1.getInt(ColumnIndex));
					} while (c1.moveToNext());
				}
			} while (c.moveToNext());
		}
		if(aitems.size()==0)return null;
		String[] items = new String[aitems.size()];
		String[] imgs = new String[aitems.size()];
		for(int i = 0 ; i < items.length ; i++){items[i]=aitems.get(i);imgs[i]=aimages.get(i);}
		int[] ida = new int[ids.size()];
		for(int i = 0 ; i < ids.size() ; i++){ida[i]=ids.get(i);}
		ArrayList<Object> oarr = new ArrayList<Object>();
		oarr.add(ida);
		oarr.add(items);
		oarr.add(imgs);
		return oarr;
	}
	
	public boolean showGroupNameBelongContact(final int idcontact){
		final ArrayList<String> aitems = new ArrayList<String>();
		final ArrayList<Integer> ids = new ArrayList<Integer>();
		final ArrayList<Integer> arr = new ArrayList<Integer>();
		Cursor c = getContentResolver().query(GroupContact.GroupContactColumns.CONTENT_URI, new String[]{GroupContact.GroupContactColumns.GROUPID}, GroupContact.GroupContactColumns.CONTACTID + "=" + idcontact, null, null);
		if (c.moveToFirst()) {        	
			int ColumnFisrt = c.getColumnIndex(GroupContact.GroupContactColumns.GROUPID);
			do {
				// Get the field values								
				int i = c.getInt(ColumnFisrt);
				Cursor c1 = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, Groups.GroupColumns._ID + "=" + i, null, null);
				if (c1.moveToFirst()) {        	
					int ColumnName = c1.getColumnIndex(Groups.GroupColumns.GROUPNAME);
					int ColumnIndex = c1.getColumnIndex(Groups.GroupColumns._ID);
					do {
						aitems.add(c1.getString(ColumnName));
						ids.add(c1.getInt(ColumnIndex));
					} while (c1.moveToNext());
				}
			} while (c.moveToNext());
		}
		if(aitems.size()==0)return false;
		String[] items = new String[aitems.size()];
		for(int i = 0 ; i < items.length ; i++){items[i]=aitems.get(i);}		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Delete group names");
		builder.setMultiChoiceItems(items, null, new OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked==true)
					arr.add(ids.get(which));
				else{
					Integer t = ids.get(which);
					if(arr.contains(t)){						
						arr.remove(t);						
					}
				}
			}
		});
		final AlertDialog alert = builder.create();
		alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.strDelete), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				for(int i = 0 ; i < arr.size() ; i++){					
					getContentResolver().delete(GroupContact.GroupContactColumns.CONTENT_URI, GroupContact.GroupContactColumns.GROUPID + "=" + arr.get(i),null);
				}
				alert.cancel();
			}
		});
		alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.strRevert), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				alert.cancel();
			}
		});		
		alert.show();
		return true;
	}
	
	public boolean showGroupNameDialog(final int idcontact){
		ArrayList<Integer> ar = new ArrayList<Integer>();
		Cursor c = getContentResolver().query(GroupContact.GroupContactColumns.CONTENT_URI, new String[]{GroupContact.GroupContactColumns.GROUPID}, GroupContact.GroupContactColumns.CONTACTID + "=" + idcontact, null, null);
		if (c.moveToFirst()) {        	
			int ColumnFisrt = c.getColumnIndex(GroupContact.GroupContactColumns.GROUPID);
			do {
				// Get the field values								
				ar.add(c.getInt(ColumnFisrt));				
			}while(c.moveToNext());
		}
		String[] items = null;
		int[] ids = null;
		if(ar.size()!=0){
			String q = "";
			for(int i = 0 ; i < ar.size() ; i++){
				if(i!=ar.size()-1)
					q+=Groups.GroupColumns._ID + "<>" + ar.get(i) + " And ";
				else
					q+=Groups.GroupColumns._ID + "<>" + ar.get(i);
			}			
			Cursor c1 = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, q, null, null);		
			String str = "", str1="";
			boolean f = true;
	        if (c1.moveToFirst()) {
	        	f = false;
				int ColumnFisrt = c1.getColumnIndex(Groups.GroupColumns.GROUPNAME);
				int ColumnSecond = c1.getColumnIndex(Groups.GroupColumns._ID);
				do {
					// Get the field values								
					str += c1.getString(ColumnFisrt);
					str +="\n";
					str1 +=c1.getInt(ColumnSecond);
					str1 +="\n";
				} while (c1.moveToNext());
			}
	        items = str.split("\n");
	        String[] s = str1.split("\n");
	        ids = new int[s.length];
	        if(f)return false;
	        for(int i = 0 ; i < s.length ; i++){ids[i] = Integer.parseInt(s[i]);}
		}		
		else{
			items = getGroupName();
			ids = getGroupId();
		}
		final int[] tids = ids;
		if(items.length==0 || items[0].length()==0)return false;		
		final ArrayList<Integer> arr = new ArrayList<Integer>();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Choose a group name");
		builder.setMultiChoiceItems(items, null, new OnMultiChoiceClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked==true)
					arr.add(tids[which]);
				else{
					Integer t = tids[which];
					if(arr.contains(t)){						
						arr.remove(t);						
					}
				}
			}
		});
		final AlertDialog alert = builder.create();
		alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.strDone), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				for(int i = 0 ; i < arr.size() ; i++){
					ContentValues values = new ContentValues();
					values.put(GroupContact.GroupContactColumns.CONTACTID, idcontact);
					values.put(GroupContact.GroupContactColumns.GROUPID, arr.get(i));
					getContentResolver().insert(GroupContact.GroupContactColumns.CONTENT_URI, values);
				}
			}
		});
		alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.strRevert), new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				alert.cancel();
			}
		});		
		alert.show();
		return true;
	}
	
	public String[] getGroupName(){
		Cursor c = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnFisrt = c.getColumnIndex(Groups.GroupColumns.GROUPNAME);			
			do {
				// Get the field values								
				str += c.getString(ColumnFisrt);
				str +="\n";							
			} while (c.moveToNext());
		}
        String[] res = str.split("\n");
        if(res.length!=0)
        	return res;
        return null;
	}
	public int[] getGroupId(){
		Cursor c = getContentResolver().query(Groups.GroupColumns.CONTENT_URI, null, null, null, null);		
		String str = "";
        if (c.moveToFirst()) {        	
			int ColumnId = c.getColumnIndex(Groups.GroupColumns._ID);			
			do {
				// Get the field values								
				str += (c.getString(ColumnId));
				str +="\n";							
			} while (c.moveToNext());
		}
        int[] res = null;
        if(str.length()>0)str = str.substring(0, str.length()-1);
        if(str.length()!=0){
        	String[] temp = str.split("\n");
        	res = new int[temp.length];		                    
        	for(int i = 0 ; i < res.length ; i++){
        		res[i] = Integer.parseInt(temp[i]);
        	}
        }
		return res;
	}
	
	@Override
    public void onCreate (Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact);
		lsv1 = (ListView)findViewById(R.id.listview1);	
		String[] arrImage = getContactImage();
		String[] arrName = getContactName();
		int[] arrId = getContactId();
		if(arrId!=null)
			lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
	}
	
	@Override
	protected void onStart ()
	{
		super.onStart();
		if(idgroup == null){
			lsv1 = (ListView)findViewById(R.id.listview1);				
			String[] arrImage = getContactImage();
			String[] arrName = getContactName();
			int[] arrId = getContactId();
			if(arrId!=null)
				lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
			else
				lsv1.setAdapter(null);
		}
		else{
			lsv1 = (ListView)findViewById(R.id.listview1);
			ArrayList<Object> res = getContactNameBelongGroup(idgroup);
			int[] arrId = (int[])res.get(0);
			String[] arrImage = (String[])res.get(2);
			String[] arrName = (String[])res.get(1);			 
			if(arrId!=null)
				lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
			else
				lsv1.setAdapter(null);
		}
	}
	
	@Override
	protected void onResume ()
	{
		super.onStart();
		if(idgroup == null){		
			lsv1 = (ListView)findViewById(R.id.listview1);				
			String[] arrImage = getContactImage();
			String[] arrName = getContactName();
			int[] arrId = getContactId();
			if(arrId!=null)
				lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
			else
				lsv1.setAdapter(null);
			}
		else{
			lsv1 = (ListView)findViewById(R.id.listview1);
			ArrayList<Object> res = getContactNameBelongGroup(idgroup);
			int[] arrId = (int[])res.get(0);
			String[] arrImage = (String[])res.get(2);
			String[] arrName = (String[])res.get(1);			 
			if(arrId!=null)
				lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
			else
				lsv1.setAdapter(null);
		}
	}
	
	@Override
    public boolean onPrepareOptionsMenu (Menu menu){
    	menu.clear();    	
		menu.add(0, Utils.MENU_ADD_CONTACT, 0, getString(R.string.strAdd)).setIcon(R.drawable.add_user);
    	menu.add(0, Utils.MENU_EDIT_CONTACT, 1, getString(R.string.strEdit)).setIcon(R.drawable.edit_user);
    	menu.add(0, Utils.MENU_DELETE_CONTACT, 2, getString(R.string.strDelete)).setIcon(R.drawable.delete_user);
    	menu.add(0, Utils.MENU_ADD_TO_GROUP, 3, getString(R.string.strAddToGroup)).setIcon(R.drawable.group_add);
    	menu.add(0, Utils.MENU_VIEW_GROUP, 4, getString(R.string.strViewToGroup)).setIcon(R.drawable.group_view); 
    	menu.add(0, Utils.MENU_CHAT, 5, getString(R.string.strChat)).setIcon(R.drawable.chat);
    	return true;
    }
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
             // When the user center presses, let them pick a contact.			 			 
			if(idgroup!=null){
				idgroup = null;
				lsv1 = (ListView)findViewById(R.id.listview1);				
				String[] arrImage = getContactImage();
				String[] arrName = getContactName();
				int[] arrId = getContactId();
				if(arrId!=null)
					lsv1.setAdapter(new adIconText(getApplicationContext(), arrImage, arrName, arrId));
				else
					lsv1.setAdapter(null);
				return true;
			}
			else{
				return super.onKeyDown(keyCode, event);
			}
		}		
		return super.onKeyDown(keyCode, event);
	}     
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {    
    	// Handle item selection    
    	switch (item.getItemId()) {  
    		case Utils.MENU_ADD_CONTACT:    	
    			Intent i = new Intent(this, ActCreateContact.class);    			
    			startActivity(i);
    			return true;
    		case Utils.MENU_EDIT_CONTACT:
    			if(lsv1 != null){
    				if(lsv1.getSelectedItemId()>-1){
    					Intent intent = new Intent(this, ActCreateContact.class);    	
    					intent.putExtra("contactbundle", prepareToEditContact((int)lsv1.getSelectedItemId()));
    					startActivity(intent);
    				}
    				else{
    					Toast.makeText(this, getString(R.string.strChooseToEdit), Toast.LENGTH_SHORT).show();
    				}
    			}
    			return true;    		 
    		case Utils.MENU_DELETE_CONTACT:
    			if(lsv1 != null){
    				if(lsv1.getSelectedItemId()>-1){
    					deleteGroupContact((int)lsv1.getSelectedItemId(), GroupContact.GroupContactColumns.CONTACTID);
    					deleteContact((int)lsv1.getSelectedItemId());    					
    				}
    				else{
    					Toast.makeText(this, getString(R.string.strChooseToDelete), Toast.LENGTH_SHORT).show();
    				}
    			}
    			return true;
    		case Utils.MENU_ADD_TO_GROUP:
    			if(lsv1 != null){
    				if(lsv1.getSelectedItemId()>-1){
    					if(showGroupNameDialog((int) lsv1.getSelectedItemId())==false){
    						Toast.makeText(this, getString(R.string.strThereNoGroupToAdd), Toast.LENGTH_SHORT).show();
    					}
    				}
    			}
    			return true;
    		case Utils.MENU_VIEW_GROUP:
    			if(lsv1 != null){
    				if(lsv1.getSelectedItemId()>-1){
    					if(showGroupNameBelongContact((int) lsv1.getSelectedItemId())==false){
    						Toast.makeText(this, getString(R.string.strThisContactHasNoGroup), Toast.LENGTH_SHORT).show();
    					}
    				}
    				else{
    					Toast.makeText(this, getString(R.string.strChooseToView), Toast.LENGTH_SHORT).show();
    				}
    			}
    			return true;
    		case Utils.MENU_CHAT:
    			if(lsv1 != null){
    				if(lsv1.getSelectedItemId()>-1){
    					Cursor c = getContentResolver().query(Contact.ContactColumns.CONTENT_URI, new String[]{Contact.ContactColumns.PHONENUMBER,Contact.ContactColumns.NICKNAME,Contact.ContactColumns.IMAGE}, Contact.ContactColumns._ID + "=" + lsv1.getSelectedItemId(), null, null);
    					if (c.moveToFirst()) {
    						int Column = c.getColumnIndex(Contact.ContactColumns.PHONENUMBER);    
    						int Column1 = c.getColumnIndex(Contact.ContactColumns.NICKNAME);
    						int Column2 = c.getColumnIndex(Contact.ContactColumns.IMAGE);
    						startActivity(new Intent(ActContact.this, ActChat.class).putExtra("arrPhone", new String[]{c.getString(Column)}).putExtra("arrNick", new String[]{c.getString(Column1)}).putExtra("arrPic", new String[]{c.getString(Column2)}));	
    					}    					
    				}
    				else{
    					Toast.makeText(this, getString(R.string.strChooseToChat), Toast.LENGTH_SHORT).show();
    				}
    			}    			    		
    			return true;
    		default:        
    			return super.onOptionsItemSelected(item);    
    	}
	}
}
